package com.swufe.lianxi;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.BreakIterator;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.ResourceBundle;

import javax.security.auth.login.LoginException;


public class RateActivity extends AppCompatActivity implements Runnable{

    private static final String TAG = "Rate";
    private float dollarRate=0.12f;
    private float euroRate=0.23f;
    private float wonRate=120f;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);
        //Intent Rate = getIntent();
        //dollarRate = Rate.getFloatExtra("dollar_key1", 0.12f);
        //euroRate = Rate.getFloatExtra("euro_key1", 0.23f);
        //wonRate = Rate.getFloatExtra("won_key1", 120f);
        //获得sp数据
        SharedPreferences sp=getSharedPreferences("myRate", Activity.MODE_PRIVATE);
        dollarRate=sp.getFloat("dollar_rate",0.12f);
        euroRate=sp.getFloat("euro_rate",0.23f);
        wonRate=sp.getFloat("won_rate",120f);
        Log.i(TAG, "onCreate:dollarRate=" + dollarRate);
        Log.i(TAG, "onCreate:euroRate=" + euroRate);
        Log.i(TAG, "onCreate:wonRate=" + wonRate);

        SharedPreferences sharePreferences=getSharedPreferences("myRate", Activity.MODE_PRIVATE);
        String updateDate =sharePreferences.getString("update_date","");
        //获取当前系统时间
        Date today = Calendar.getInstance().getTime();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd");
        final  String todayStr=sdf.format(today);
        //进行日期判断
        Log.i(TAG, "onCreate: sp updateDate="+updateDate);
        Log.i(TAG, "onCreate: todayStr="+todayStr);
        //判断时间
        if(!todayStr.equals(updateDate)){
            Log.i(TAG, "onCreate: 需要更新");
            //开启子线程
            Thread t=new Thread(this);
            t.start();
        }else{
            Log.i(TAG, "onCreate: 不需要更新");
        }

        //开启子线程运行
        Thread t = new Thread(this);
        t.start();
        handler = new Handler(Looper.myLooper()) {//handler 传递消息
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 5) {
                    //String str = (String) msg.obj;
                    //dollarRate=bundle.getFloat("dollarRate");
                    //Log.i(TAG, "handleMessage:str=" + str);
                    Bundle bdl = (Bundle) msg.obj;
                    dollarRate = bdl.getFloat("dollar-rate");
                    euroRate = bdl.getFloat("euro-rate");
                    wonRate = bdl.getFloat("won-rate");
                    Log.i(TAG, "handleMessage: dollarRate:" + dollarRate);
                    Log.i(TAG, "handleMessage: euroRate:" + euroRate);
                    Log.i(TAG, "handleMessage: wonRate:" + wonRate);
                    Toast.makeText(RateActivity.this, "汇率已更新", Toast.LENGTH_SHORT).show();
                    //保存更新的日期
                    SharedPreferences sp=getSharedPreferences("myRate", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor=sp.edit();
                    editor.putFloat("dollar_rate",dollarRate);
                    editor.putFloat("euro_rate",euroRate);
                    editor.putFloat("won_rate",wonRate);
                    editor.putString("update_date",todayStr);
                    editor.apply();
                    Log.i(TAG,"onActivityResult:save to sp"+"save to sp");
                }
                super.handleMessage(msg);
            }
        };
    }

    public void click(View btn) {
        Log.i(TAG, "click");
        EditText input = findViewById(R.id.rmb);
        String str = input.getText().toString();
        if (str.length() == 0) {
            Toast.makeText(this, "请输入金额", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.i(TAG, "click str=" + str);
        float inp = Float.parseFloat(str);
        float r = 0.0f;
        if (btn.getId() == R.id.dollar) {
            r = inp * dollarRate;
        } else if (btn.getId() == R.id.euro) {
            r = inp * euroRate;
        } else {
            r = inp * wonRate;
        }
        TextView result = findViewById(R.id.result);
        result.setText("兑换：" + r);
    }
    public void openone(View btn){
        openConfig();
    }

    private void openConfig(){
    Log.i(TAG,"openconfig:");
    Intent config=new Intent(this,ConfigActivity2.class);
    config.putExtra("dollar_key",dollarRate);
    config.putExtra("euro_key",euroRate);
    config.putExtra("won_key",wonRate);
    Log.i(TAG,"openone:dollarRate:"+dollarRate);
    Log.i(TAG,"openone:euroRate:"+euroRate);
    Log.i(TAG,"openone:wonRate:"+wonRate);
    //startActivity(config);
  startActivityForResult(config,1);
}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.rate,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.menu_setting){
            openConfig();
        }else if(item.getItemId()==R.id.open_list){
            Intent list=new Intent(this,RatelistActivity.class);
            //Intent list=new Intent(this,MyLIstActivity.class);
            startActivity(list);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            if(requestCode==1&&requestCode==2){
                Bundle bdl=data.getExtras();
                dollarRate=bdl.getFloat("dollar_key");
                euroRate=bdl.getFloat("euro_key");
                wonRate=bdl.getFloat("won_key");
                Log.i(TAG,"onActivityResult:dollarRate="+dollarRate);
                Log.i(TAG,"onActivityResult:euroRate="+euroRate);
                Log.i(TAG,"onActivityResult:wonRate="+wonRate);
                //保存新的汇率到对象中
                SharedPreferences sp=getSharedPreferences("myRate", Activity.MODE_PRIVATE);
                SharedPreferences.Editor editor=sp.edit();
                editor.putFloat("dollar_rate",dollarRate);
                editor.putFloat("euro_rate",euroRate);
                editor.putFloat("won_rate",wonRate);
                editor.apply();
                Log.i(TAG,"onActivityResult:save to sp"+"save to sp");
            }

        super.onActivityResult(requestCode, resultCode, data);
    }

    public void run() {
        Log.i(TAG, "run:run()....");
        for (int i = 1; i < 6; i++) {
            Log.i(TAG, "run:i=" + i);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //获取Msg对象，用于返回主线程
        //Message msg = handler.obtainMessage(5);
        //msg.obj = "Hello from run()";
        //handler.sendMessage(msg);
        //获取网络数据
        //URL url = null;
        //try {
            //url = new URL("https://www.usd-cny.com/icbc.htm");
            //HttpURLConnection http = (HttpURLConnection) url.openConnection();
            //InputStream in = http.getInputStream();
            //String html=inputStream2String(in);
            //Log.i(TAG,"run:html="+html);
        //} catch (MalformedURLException e) {
            //e.printStackTrace();
        //} catch (IOException e) {
            //e.printStackTrace();
        //}
        Bundle bundle = new Bundle();
        Document doc = null;
        try {
            String url = "https://www.boc.cn/sourcedb/whpj/ ";
            doc = Jsoup.connect(url).get();
            Log.i(TAG, "run: " + doc.title());
            Elements tables = doc.getElementsByTag("table");
            Element table1 = tables.get(1);
            Log.i(TAG, "run: table1="+table1);
            //Element table6 = tables.get(5);
            //Log.i(TAG, "run: table6=" + table6);
            //获取TD中的数据
            //Elements tds = table6.getElementsByTag("td");
            Elements tds = table1.getElementsByTag("td");
            for(int i=0;i<tds.size();i+=8) {
                Element td1 = tds.get(i);
                Element td2 = tds.get(i + 5);
                String str1 = td1.text();
                String val = td2.text();
                Log.i(TAG, "run: " + str1 + "==>" + val);
                    float v = 100f / Float.parseFloat(val);
                    if ("美元".equals(str1)) {
                        bundle.putFloat("dollar-rate", v);
                    } else if ("欧元".equals(str1)) {
                        bundle.putFloat("euro-rate", v);
                    } else if ("韩国元".equals(str1)) {
                        bundle.putFloat("won-rate", v);
                    }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Message msg = handler.obtainMessage(5);
        msg.obj = bundle;
        handler.sendMessage(msg);
    }
}